package com.qidian.common.beans;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import com.qidian.common.Constants;
import com.qidian.common.TableMeta;

public class UserBean implements ISyncBean
{
    Long userId = -1L;
    String userName ;
    String password ;
    AtomicInteger point = new AtomicInteger(0);
    AtomicInteger pointIncrement = new AtomicInteger(0);
    AtomicInteger usedPoint = new AtomicInteger(0);
    AtomicInteger usedPointIncrement = new AtomicInteger(0);
    long lastTime = System.currentTimeMillis() ;
    long birthTime = System.currentTimeMillis() ;
    volatile int status  ;
    String QQ ;
    String email ;
    // 支付宝
    String zhifubao;
    // 电话
    String phone;
    // 开发者类型: 作者、代理
    int userType ;
    // 返点
	volatile double returnPoint = 0.0f;
	AtomicLong returnPointIncr1000 = new AtomicLong(0L) ;
	// 返点比率
	volatile double returnRatio = 0.0f ;
	
    volatile boolean needSync = false ;
    
    int newAccountToday = 0 ;
    int newRechargeCardToday = 0 ;
    

    
    
    /**
     * 重置计数
     * */
    public void resetCount()
    {
    	newAccountToday = 0 ;
        newRechargeCardToday = 0 ;
    }
    /**
     * 
     * 
     * */
    public void increaseAccount()
    {
    	newAccountToday ++ ;
    }
    /**
     * 是否当天创建太多的子账号
     * 
     * */
    public boolean isYa()
    {
    	return newAccountToday > Constants.max_account_per_day;
    }
    /**
     * 
     * */
    public void increaseRechargeCard()
    {
    	newRechargeCardToday ++ ;
    }
    /**
     * 是否当天创建太多的充值卡
     * 
     **/
    public boolean isYr()
    {
    	return newRechargeCardToday > Constants.max_recharge_card_per_day ;
    }
	public String getQQ() {
		return QQ;
	}
	public void setQQ(String qq) {
		QQ = qq;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public long getUserId() {
		return userId;
	}
	public void setUserId(Long userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public int getPoint() {
		return point.get();
	}
	public void setPoint(int point) {
		this.point.set(point);
	}
	public int getLeftPoint()
	{
		return point.get() - usedPoint.get() ;
	}
	public int getUsedPoint() {
		return usedPoint.get();
	}
	public void setUsedPoint(int usedPoint) {
		this.usedPoint.set(usedPoint);
	}
	
	/**
	 * 减少已用点数
	 * 
	 * */
	public synchronized void decreaseUsedPoint(int point)
    {
    	usedPoint.addAndGet(-point) ;
    	usedPointIncrement.addAndGet(-point) ;
    	needSync = true ;
    }
	
	/**
	 * 增加已用点数
	 * 
	 * */
	public void increaseUsedPoint(int point)
	{
    	usedPoint.addAndGet(point) ;
    	usedPointIncrement.addAndGet(point) ;
		needSync = true ;
	}
	
	/**
	 * 增加返点
			自定义点数>=平台扣点, 返点=平台扣点*返点率 + (自定义扣点-平台扣点)*0.90
			自定义点数<平台扣点, 返点=自定义扣点*返点率-(平台扣点-自定义扣点) 
			1:主账号扣除自定义点数,子账号扣除
			2:主账号扣除平台点数
	 * @param point 平台扣点
	 * @param point 自定义扣点
	 * 
	 * */
	public void increaseReturnPoint(double point,double uPoint)
	{
		double deltaReturnPoint = 0.0f ;
		if (uPoint >= point)
			deltaReturnPoint = point*returnRatio + (uPoint-point)*(1-Constants.extra_return_ratio) ;
		else
			deltaReturnPoint = uPoint*returnRatio - (point-uPoint) ;
//		System.out.println(deltaReturnPoint) ;
		returnPoint += deltaReturnPoint ;
		returnPointIncr1000.addAndGet((long)(deltaReturnPoint*1000)) ;
		needSync = true ;
	}
	/**
	 * 减少返点
			自定义点数>=平台扣点, 返点=平台扣点*返点率 + (自定义扣点-平台扣点)*0.90
			自定义点数<平台扣点, 返点=自定义扣点*返点率-(平台扣点-自定义扣点) 
			1:主账号扣除自定义点数,子账号扣除
			2:主账号扣除平台点数
	 * @param point 平台扣点
	 * @param point 自定义扣点
	 * 
	 * */
	public void decreaseReturnPoint(double point, double uPoint)
	{
		double deltaReturnPoint = 0.0f ;
		if (uPoint >= point)
			deltaReturnPoint = point*returnRatio + (uPoint-point)*(1-Constants.extra_return_ratio) ;
		else
			deltaReturnPoint = uPoint*returnRatio - (point-uPoint) ;
		
		deltaReturnPoint = -deltaReturnPoint ;
//		System.out.println(deltaReturnPoint) ;
		returnPoint += deltaReturnPoint ;
		returnPointIncr1000.addAndGet((long)(deltaReturnPoint*1000)) ;
		needSync = true ;		
	}
	
	/**
	 * 返点转换为可用点数
	 * @param point 需要转换的返点数,如果需要转换的返点数少于可用返点数,全部转换
	 * @return 返回实际转换的返点数
	 * */
	public double returnPointToLeftPoint(double point)
	{
		if (point <= 0.0)
			point = 0.0 ;
		
		if (returnPoint < point)
			point = returnPoint ;
		
		returnPoint -= point ;
		returnPointIncr1000.addAndGet((long)(point*1000)) ;
		
		return point ;
	}
	
	public static UserBean toUserBean(ResultSet rs) throws SQLException 
	{
		UserBean userBean = new UserBean() ;
		userBean.setUserId(rs.getLong(TableMeta.column_user_id)) ;
		userBean.setUserName(rs.getString(TableMeta.column_user_name)) ;
		userBean.setPassword(rs.getString(TableMeta.column_password)) ;
		userBean.setPoint(rs.getInt(TableMeta.column_point)) ;
		userBean.setUsedPoint(rs.getInt(TableMeta.column_point_used)) ;
		userBean.setBirthTime(rs.getLong(TableMeta.column_birth_time));
		userBean.setStatus(rs.getInt(TableMeta.column_status));
		userBean.setLastTime(rs.getLong(TableMeta.column_last_time)) ;
		userBean.setQQ(rs.getString(TableMeta.column_QQ));
		userBean.setEmail(rs.getString(TableMeta.column_email)) ;
		userBean.setStatus(rs.getInt(TableMeta.column_status)) ;
		userBean.setZhifubao(rs.getString(TableMeta.column_zhifubao)) ;
		userBean.setPhone(rs.getString(TableMeta.column_phone)) ;
		userBean.setUserType(rs.getInt(TableMeta.column_user_type)) ;
		userBean.setReturnPoint(rs.getDouble(TableMeta.column_return_point)) ;
		userBean.setReturnRatio(rs.getDouble(TableMeta.column_return_ratio)) ;
		return userBean;
	}
	
    @Override
    public PreparedStatement getPreparedStatement(Connection conn)
            throws SQLException
    {
        final String sql = " update " + TableMeta.table_user + 
        				" set " + TableMeta.column_point_used + " =  " + TableMeta.column_point_used + " + ? ,"+ 
        					TableMeta.column_point + " =  " + TableMeta.column_point + " + ? ,"+
        					TableMeta.column_return_point + " = "+ TableMeta.column_return_point + " + ? , "+
        					TableMeta.column_return_ratio + " = ? , " +
        					TableMeta.column_last_time + " = ?, "+
        					TableMeta.column_status + " = ? " +
                        " where " + TableMeta.column_user_id + " = ? ";
        
        return conn.prepareStatement(sql);
    }
    
    @Override
    public boolean needSynchronized()
    {
        return needSync;
    }
    
    @Override
    public boolean setParameters(PreparedStatement ps)
    {
        try
        {
            ps.setInt(1, usedPointIncrement.getAndSet(0)) ;
            ps.setInt(2, pointIncrement.getAndSet(0)) ;
            ps.setDouble(3, returnPointIncr1000.getAndSet(0L)*1.0/1000.0) ;
            ps.setDouble(4, returnRatio) ;
            ps.setLong(5, lastTime) ;
            ps.setInt(6, status) ;
            ps.setLong(7, userId) ;
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            try 
            {
				ps.clearParameters() ;
			}
            catch (SQLException e1) 
            {
			}
            return false ;
        }
        // 重置 
        needSync = false ;
        return true;
    }
    
    public String toString()
    {
    	StringBuffer sb = new StringBuffer(128) ;
    	sb.append("UserId:").append(this.userId).append(",UserName:").append(this.userName) ;
    	sb.append(",Points:").append(this.point).append(",UsedPoints:").append(this.usedPoint) ;
    	sb.append(",UsedPointIncrement:").append(this.usedPointIncrement) ;
    	return sb.toString() ;
    }
    
    public String generateMaskCode(int points)
    {
    	return null ;
    }
    /**
     * 用户名只能包含数字、字母、下划线,最长为20位,最短为6位。
     * 
     * */
    public static boolean isValidUserName(String userName)
    {
    	return userName != null && userName.matches("[0-9a-zA-Z_]{6,20}") ;
    }
    public static boolean isValidZhifubao(String zhifubao)
    {
    	return zhifubao != null && zhifubao.matches("[0-9\\-_a-zA-Z@.]{6,64}");
    }
    public static boolean isValidPhone(String phone)
    {
    	return phone != null && phone.matches("[0-9]{7,12}") ;
    }
    public static boolean isValidQQ(String qq)
    {
    	return qq != null && qq.matches("[0-9]{4,12}") ;
    }
    public static boolean isValidEmail(String email)
    {
    	return email != null && email.matches("[0-9\\-_a-zA-Z@.]{6,32}") ;
    }
    public static void main(String[] args)
    {
    	String test = "12+3-21342" ;
    	System.out.println(test.matches("[0-9\\-+]{6,20}")) ;
    	test = "new_-_20'07@sina.com.cn" ;
    	System.out.println(test.matches("[0-9\\-_a-zA-Z@.]{6,32}")) ;
    	
    }
    
    /**
     * 密码只能包含数字、字母、下划线,最长为20位,最短为6位。
     * 
     * */
    public static boolean isValidPassword(String password)
    {
    	return password != null && password.matches("[0-9a-zA-Z_]{6,20}") ;
    }

    /**
     * 增加可用点数
     * */
	public void increasePoint(int point) 
	{
		if (this.point.get()+point <= 0)
		{
			System.out.println("Over flow");
			return ;
		}
		this.point.addAndGet(point) ;
		pointIncrement.addAndGet(point) ;
		this.needSync = true ;
	}
	public long getBirthTime() {
		return birthTime;
	}
	public void setBirthTime(long birthTime) {
		this.birthTime = birthTime;
	}
	public int getStatus() {
		return status;
	}
	public void setStatus(int status) {
		this.status = status;
	}
	/**
	 * 删除帐号
	 * 
	 * */
	public void setDeleted()
	{
		this.status = -1 ;
		this.needSync = true ;
	}

	/**
	 * 冻结用户
	 * 
	 * */
	public void freeze()
	{
		this.status = 1 ;
		needSync = true ;
	}
	/**
	 * 解冻用户
	 * 
	 * */
	public void unfreeze()
	{
		this.status = 0;
		needSync = true ;
	}
	
	public boolean isFreeze()
	{
		return this.status == 1 ;
	}
	
	public long getLastTime() {
		return lastTime;
	}
	public void setLastTime(long lastTime) {
		this.lastTime = lastTime;
	}
	public boolean isDeleted()
	{
		return this.status == -1 ;
	}
	public double getReturnPoint() {
		return returnPoint;
	}
	public void setReturnPoint(double returnPoint) {
		this.returnPoint = returnPoint;
	}
	public double getReturnRatio() {
		return returnRatio;
	}
	public void setReturnRatio(double returnRatio) {
		this.returnRatio = returnRatio;
		needSync = true ;
	}
	public String getZhifubao() {
		return zhifubao;
	}
	public void setZhifubao(String zhifubao) {
		this.zhifubao = zhifubao;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public int getUserType() {
		return userType;
	}
	public void setUserType(int userType) {
		this.userType = userType;
	}
	/**
	 * 减少返点数量
	 * 	用于返点兑换
	 * 
	 * */
	public void decreaseReturnPoint(int point) 
	{
		this.returnPoint -= point ;
		this.returnPointIncr1000.addAndGet(-point*1000) ;
		this.needSync = true ;
	}
	
	
	public boolean isSupperUser()
	{
		return Constants.super_user_name.equalsIgnoreCase(userName) ;
	}
	
}
